<template>
  <a-modal
    title="新建"
    :width="840"
    centered
    :visible="visible"
    :confirmLoading="loading"
    @ok="modalOk"
    @cancel="() => { $emit('cancel') }"
  >
    <a-spin :spinning="loading">
      <a-form :form="form" v-bind="formLayout">
        <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
        <a-form-item v-show="model && model.id" label="主键ID">
          <a-input v-decorator="['id', { initialValue: model.id }]" disabled />
        </a-form-item>
        <a-form-item label="">
          <a-button type="primary" @click="selectRecord">选择发票</a-button>
        </a-form-item>
        <s-table
          ref="table"
          :columns="columns"
          :data="loadData"
          :row-key="(record)=>record.id"
          :showPagination="false"
        >
        </s-table>
      </a-form>
    </a-spin>
    <SelectRecord :visible="selectRecordVisible" :model="this.model" @cancel="()=>{this.selectRecordVisible=false}" @OnSelect="onSelectRecord" />
  </a-modal>
</template>

<script>
// 审核状态 0=待审核 1=待开票 2=待发行 3=已完成
import difference from 'lodash/difference'
// import pick from 'lodash.pick'
import { getRecord, getRecordLists, getDeliverylies, putDeliveries } from '@/api/manage'
import SelectRecord from './SelectRecord'
import { notification } from 'ant-design-vue'
import { STable } from '@/components'
// import { resolve } from 'url';
// import { addDeliveries, putDeliveries, getRecordLists, getStationRecord } from '@/api/manage'
const fields = ['id', 'recordId']

const mockData = []
for (let i = 0; i < 20; i++) {
  mockData.push({
    key: i.toString(),
    title: `content${i + 1}`,
    description: `description of content${i + 1}`,
    disabled: i % 4 === 0
  })
}

const originTargetKeys = mockData.filter(item => +item.key % 3 > 1).map(item => item.key)

const leftTableColumns = [
  {
    dataIndex: 'title',
    title: 'Name'
  },
  {
    dataIndex: 'description',
    title: 'Description'
  }
]
const rightTableColumns = [
  {
    dataIndex: 'title',
    title: 'Name'
  },
  {
    dataIndex: 'description',
    title: 'Description'
  }
]

export default {
  name: 'BandTicket',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 7 },
        sm: { span: 2 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 22 }
      }
    }
    return {
      selectRecordVisible: false,
      displayList: [],
      thisRecords: [],
      showSearch: false,
      leftColumns: leftTableColumns,
      rightColumns: rightTableColumns,
      targetKeys: originTargetKeys,
      pagination: { pageSize: 2, pageNum: 1 },
      // targetKeys: [],
      // selectedKeys: [],
      targetSelectedKeys: [],
      recordList: [],
      recordListRight: [],
      originRecordList: [],
      form: this.$form.createForm(this),
      loadData: (parameter) => {
        console.log(this.model)
        return new Promise((resolve, reject) => {
          resolve()
        }).then(res => {
          console.log(this.thisRecords)
          return {
            data: this.thisRecords,
            totalCount: this.thisRecords.length,
            pageNo: 1,
            pageSize: 10
          }
        })
      },
      columns: [
        {
          title: '#',
          dataIndex: 'id'
        },
        {
          title: '发票流水号',
          dataIndex: 'fpqqlsh'
        },
        {
          title: '发票审核状态',
          dataIndex: 'submitState'
        },
        {
          title: '发票金额',
          dataIndex: 'totalPrice'
        }
      ],
      memberList: [],
      customerList: [],
      stationRecordList: []
    }
  },
  components: {
    STable,
    SelectRecord
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    // 当 model 发生改变时，为表单设置值
    // const _self = this
    // this.$watch('model', (news) => {
    //   this.form = this.$form.createForm(this)
    // })
  },
  watch: {
    visible (news) {
      if (news) {
        getDeliverylies(this.model.id).then(res => {
          this.thisRecords = []
          this.thisRecords.push(res.data.record)
          console.log(this.thisRecords)
          this.$refs.table.refresh(true)
        })
      }
    }
  },
  methods: {
    selectRecord () {
      this.selectRecordVisible = true
    },
    toSelect () {
      alert('123')
      // if (itemDisabled || listDisabled) return
      // itemSelect(key, !selectedKeys.includes(key))
    },
    filterData (leftData, rightData) {
      this.recordList = leftData.filter((value, index) => {
        const flagBoolean = rightData.find(item => {
          return item.id === value.id
        })
        if (flagBoolean != null) {
        } else {
          return value
        }
      })
    },
    init () {
      this.displayList = []
      getRecordLists(this.pagination).then(res => {
        res.data.forEach((item) => {
          item.key = item.id + ''
          item.title = item.fpqqlsh + ''
          item.description = item.fpqqlsh + ''
          item.disabled = false
          this.recordList.push(item)
        })
        this.filterData(this.recordList, this.recordListRight)
      })
    },
    loadMore () {
      this.pagination.pageNum += 1
      this.init()
    },
    pageChange () {
      this.recordList = []
    },
    onChange (nextTargetKeys) {
      this.targetKeys = nextTargetKeys
    },

    triggerDisable (disabled) {
      this.disabled = disabled
    },

    triggerShowSearch (showSearch) {
      this.showSearch = showSearch
    },
    getRowSelection ({ disabled, selectedKeys, itemSelectAll, itemSelect }) {
      return {
        getCheckboxProps: item => ({ props: { disabled: disabled || item.disabled } }),
        onSelectAll (selected, selectedRows) {
          const treeSelectedKeys = selectedRows
            .filter(item => !item.disabled)
            .map(({ key }) => key)
          const diffKeys = selected
            ? difference(treeSelectedKeys, selectedKeys)
            : difference(selectedKeys, treeSelectedKeys)
          itemSelectAll(diffKeys, selected)
        },
        onSelect ({ key }, selected) {
          itemSelect(key, selected)
        },
        selectedRowKeys: selectedKeys
      }
    },

    handleChange (nextTargetKeys, direction, moveKeys) {
      this.targetKeys = nextTargetKeys
      if (direction === 'right') {
        const testData = nextTargetKeys.filter((value, index) => this.recordList.find((item) => item.id === parseInt(value)))
        for (let i = 0; i < this.recordList.length; i++) {
          const item = this.recordList[i]
          console.log(item)
          if (testData.findIndex(_item => _item === item.id + '') >= 0) {
            // 从右侧加入
            this.recordListRight.push(item)
            // 从左侧删除
            this.recordList.splice(i, 1)
            i--
          }
        }
      } else {
        const tempDiff = this.recordListRight.filter((value, index) => moveKeys.find(item => item === value.key))
        // this.recordList = this.recordList.concat(tempDiff)
        for (let i = 0; i < this.recordListRight.length; i++) {
          const item = this.recordListRight[i]
          if (tempDiff.findIndex(_item => _item.key === item.key) >= 0) {
            // 从右侧加入
            this.recordList.push(item)
            // 从左侧删除
            this.recordListRight.splice(i, 1)
            i--
          }
        }
        console.log(getRecord)
      }
      console.log('targetKeys: ', nextTargetKeys)
      console.log('direction: ', direction)
      console.log('moveKeys: ', moveKeys)
    },
    handleSelectChange (sourceSelectedKeys, targetSelectedKeys) {
      // this.selectedKeys = [...sourceSelectedKeys, ...targetSelectedKeys]

      console.log('sourceSelectedKeys: ', sourceSelectedKeys)
      console.log('targetSelectedKeys: ', targetSelectedKeys)
    },
    handleScroll () {
      // console.log(putDeliveries, addDeliveries)
    },
    onSelectRecord (record) {
      this.selectRecordVisible = false
      this.thisRecords = []
      this.thisRecords.push(record)
      this.$refs.table.refresh(true)
    },
    modalOk () {
      const dict = this.model
      dict.recordId = (this.thisRecords.length <= 0) ? null : this.thisRecords[0].id
      putDeliveries(dict.id, dict).then(res => {
        notification.success({
          message: '提示',
          description: '更新发票成功'
        })
        this.$emit('cancel')
      }).catch(e => {
        notification.error({
          message: '提示',
          description: '更新发票失败'
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
